package org.example.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;


import cn.hutool.crypto.SecureUtil;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.aicloud.util.MinIoUtil;
import org.example.aicloud.util.NameUtil;
import org.example.aicloud.util.ResultAjax;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.lang.model.element.Name;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private MinIoUtil minIoUtil;



    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 生成验证码
     * @return
     */
    @RequestMapping("/create")
    public ResultAjax creatCaptcha(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, IOException {
        String url = "";
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        String fileName = NameUtil.getCaptchaName(request);

        try(InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())) {
            url =   minIoUtil.upload(fileName, inputStream, "image/png");
            String code = lineCaptcha.getCode();
            redisTemplate.opsForValue().set(fileName,code,60, TimeUnit.SECONDS); //将名称和对应的验证码存入redis，按String类型存储的此处,并设置过期时间为60s
        }
        return ResultAjax.success(url);
    }
}
